package com.dfec.book.exception;

import com.dfec.book.util.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Objects;


/**
 * 自定义异常处理类
 * @author tangrg
 * @email 1446232546@qq.com
 * @date 2025-06-19 14:42:17
 */
@RestControllerAdvice
public class ServiceExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e) {
        AjaxResult r = new AjaxResult();
        r.setCode(e.getCode());
        r.setMsg(e.getMsg());
        return r;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public AjaxResult handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return AjaxResult.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public AjaxResult handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return AjaxResult.error("数据库中已存在该记录");
    }


    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return AjaxResult.error();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        return AjaxResult.error("500", Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request) {
        String uri = request.getRequestURI();
        logger.error("请求地址'{}',不支持'{}'请求", uri, e.getMethod());
        return AjaxResult.error(e.getMessage());
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public AjaxResult handleSqlIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e,
                                                          HttpServletRequest request) {
        logger.error("主键重复了 "+e.getMessage());
        return AjaxResult.error(e.getMessage());
    }


}
